package controllers

import (
	"go-chat/common"
	"go-chat/model"
	"go-chat/services"
	"go-chat/utils"

	"github.com/gin-gonic/gin"
)

type UserController struct { //用户控制层
}

type LoginRequest struct {
	ID       uint   `json:"id,omitempty"`
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

var userService services.UserService

func (controllers *UserController) Login(c *gin.Context) { //用户登录
	req, ok := common.BindJSON[LoginRequest](c)
	if !ok {
		return // 参数错误已响应
	}
	// 处理业务逻辑，验证密码
	res, code := userService.Login(req.Username, req.Password)
	if code == 200 {
		common.Success(c, res)
	} else {
		common.Fail(c, 402, "用户名或密码错误")
	}
}

func (controllers *UserController) Register(c *gin.Context) { //用户注册
	req, ok := common.BindJSON[model.User](c)
	if !ok {
		return // 参数错误已响应
	}
	// 处理业务逻辑
	res, code := userService.Register(req)
	if code == 200 {
		common.Success(c, res)
	} else {
		common.Fail(c, code, res)
	}
}

func (controllers *UserController) GetUserInfo(c *gin.Context) { //获取用户信息
	// 处理业务逻辑，验证密码
	id := utils.GetID(c)
	res, code := userService.GetUserInfo(id)
	if code == 200 {
		common.Success(c, res)
	} else {
		common.Fail(c, 402, "用户名或密码错误")
	}
}

func (controllers *UserController) UpdateUserInfo(c *gin.Context) { //修改用户信息
	id := utils.GetID(c)
	req, ok := common.BindJSON[model.User](c)
	if !ok {
		return // 参数错误已响应
	}
	// 处理业务逻辑
	res, code := userService.UpdateUserInfo(req, id)
	if code == 200 {
		common.Success(c, res)
	} else {
		common.Fail(c, 402, "信息更新失败！")
	}
}
